package JUC.多线程.自定义线程池;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashSet;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author CKC
 * @DateTime 2021/6/10 19:34
 * <p>
 * 自定义线程池
 */
public class TestPool {
    public static void main(String[] args) {
        ThreadPool threadPool = new ThreadPool(5,
                1000L, TimeUnit.MILLISECONDS, 10);
        for (int i = 0; i < 50; i++) {
            int j = i;
            threadPool.execute(() -> {
                System.out.println(Thread.currentThread().getName() + "\t" + j);
            });
        }
    }
}


class ThreadPool {
    //任务队列
    private BlockingQueue<Runnable> taskQueue;
    //线程集合
    private HashSet<Worker> workers = new HashSet();
    
    private int coreSize;
    
    private long timeOut;
    
    private TimeUnit timeUnit;
    
    //执行任务
    public void execute(Runnable task) {
        //当任务数没有超过coreSize时，直接交给worker对象执行
        //如果任务数超过coreSize时，缴入到任务队列
        synchronized (workers) {
            if (workers.size() < coreSize) {
                Worker worker = new Worker(task);
                System.out.println(Thread.currentThread().getName() + "\t" + "新增 worker 对象" + worker + "\t" + task);
                workers.add(worker);
                worker.start();
            } else {
                System.out.println(Thread.currentThread().getName() + "\t" + "加入到任务队列:" + task);
                taskQueue.put(task);
            }
        }
    }
    
    public ThreadPool(int coreSize, long timeOut, TimeUnit timeUnit, int queueCapacity) {
        this.coreSize = coreSize;
        this.timeOut = timeOut;
        this.timeUnit = timeUnit;
        this.taskQueue = new BlockingQueue<>(queueCapacity);
    }
    
    class Worker extends Thread {
        private Runnable task;
        
        public Worker(Runnable task) {
            this.task = task;
        }
        
        
        @Override
        public void run() {
            //执行任务
            //1. 当task不为空,执行任务
            //2. 当task执行完毕,在接着从任务队列获取任务并执行
//            while (task != null || (task = taskQueue.take()) != null) {
            while (task != null || (task = taskQueue.poll(timeOut,timeUnit)) != null) {
                try {
                    System.out.println(Thread.currentThread().getName() + "\t" + "正在执行..." + task);
                    task.run();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    task = null;
                }
            }
            synchronized (workers) {
                System.out.println(Thread.currentThread().getName() + "\t" + "worker 被移除 " + this);
                workers.remove(this);
            }
        }
    }
}

class BlockingQueue<T> {
    //1.任务队列
    private Deque<T> queue = new ArrayDeque<>();
    
    //2. 锁
    private Lock lock = new ReentrantLock();
    
    //3. 生产者条件变量
    private Condition fullWaitSet = lock.newCondition();
    
    //4. 消费者条件变量
    private Condition emptyWaitSet = lock.newCondition();
    
    //5. 容量
    private int capacity;
    
    public BlockingQueue(int capacity) {
        this.capacity = capacity;
    }
    
    //阻塞添加
    public void put(T element) {
        lock.lock();
        try {
            while (queue.size() == capacity) {
                try {
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(element);
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }
    
    
    //带超时的阻塞获取
    public T poll(long timeout, TimeUnit unit) {
        lock.lock();
        try {
            //将时间转换成纳秒
            long l = unit.toNanos(timeout);
            while (queue.isEmpty()) {
                try {
                    if (l <= 0) {
                        return null;
                    }
                    /**
                     * awaitNanos  的返回值：
                     * nanosTimeout值减去等待从该方法返回所花费的时间的估计值。
                     * 可以使用正值作为对该方法的后续调用的参数，以完成等待所需的时间。
                     * 小于或等于零的值表示没有剩余时间
                     */
                    l = emptyWaitSet.awaitNanos(l);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }
    
    //阻塞获取
    public T take() {
        lock.lock();
        try {
            while (queue.isEmpty()) {
                try {
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }
    
    
    //获取大小
    public int size() {
        lock.lock();
        try {
            return queue.size();
        } finally {
            lock.unlock();
        }
    }
}